package com.edu.servlet;

import com.edu.service.AdminPostService;
import com.edu.bean.Post;
import com.edu.bean.PostReply;
import com.edu.bean.User;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/post/*")
public class AdminPostServlet extends HttpServlet {
    private AdminPostService adminPostService = new AdminPostService();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/list":
                listPosts(request, response);
                break;
            case "/view":
                viewPost(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/delete":
                deletePost(request, response);
                break;
            case "/reply":
                replyPost(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    private void listPosts(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int page = 1;
        int limit = 10;
        String pageStr = request.getParameter("page");
        String title = request.getParameter("title");
        String typeStr = request.getParameter("type");

        if (pageStr != null && !pageStr.isEmpty()) {
            page = Integer.parseInt(pageStr);
        }

        Integer type = null;
        if (typeStr != null && !typeStr.isEmpty()) {
            type = Integer.parseInt(typeStr);
        }

        Map<String, Object> result = adminPostService.adminListPosts(page, limit, title, type);
        List<Post> postList = (List<Post>) result.get("list");
        int total = (Integer) result.get("total");

        request.setAttribute("postList", postList);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", (int) Math.ceil((double) total / limit));
        request.setAttribute("totalCount", total);

        request.getRequestDispatcher("/admin/post-list.jsp").forward(request, response);
    }

    private void viewPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            int postId = Integer.parseInt(idStr);
            Post post = adminPostService.adminGetPost(postId);
            List<PostReply> replyList = adminPostService.adminListReplies(postId);

            if (post != null) {
                request.setAttribute("post", post);
                request.setAttribute("replyList", replyList);
                request.getRequestDispatcher("/admin/post-view.jsp").forward(request, response);
                return;
            }
        }
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

    private void deletePost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            boolean success = adminPostService.adminDeletePost(Integer.parseInt(idStr));
            result.put("success", success);
            if (!success) {
                result.put("message", "删除失败");
            }
        } else {
            result.put("success", false);
            result.put("message", "参数错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }

    private void replyPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        try {
            // 从session中获取adminUser对象
            User adminUser = (User) request.getSession().getAttribute("adminUser");
            if (adminUser == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                objectMapper.writeValue(response.getWriter(), result);
                return;
            }

            PostReply reply = new PostReply();
            reply.setPostId(Integer.parseInt(request.getParameter("postId")));
            reply.setUserId(adminUser.getUserId()); // 使用adminUser对象的userId
            reply.setContent(request.getParameter("content"));

            boolean success = adminPostService.adminAddReply(reply);
            result.put("success", success);
            if (!success) {
                result.put("message", "回复失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }
}